package cn.smxy.ln.controller;

import cn.hutool.core.date.DateUtil;
import cn.smxy.ln.common.lang.Result;
import cn.smxy.ln.common.utils.RedisUtil;
import cn.smxy.ln.pojo.OssDto;
import cn.smxy.ln.pojo.WorkContent;
import cn.smxy.ln.pojo.WorkProve;
import cn.smxy.ln.pojo.WorkRegister;
import cn.smxy.ln.service.OssService;
import cn.smxy.ln.service.WorkProveService;
import cn.smxy.ln.service.WorkRegisterService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.util.*;

/**
 * @author ln
 * @date 2022年05月24日 19:42
 */
@RestController
@RequestMapping("/workprove")
public class WorkProveController {

    @Autowired
    WorkProveService workProveService;

    @Autowired
    WorkRegisterService workRegisterService;

    @Autowired
    RedisUtil redisUtil;

    @Autowired
    OssService ossService;

    @GetMapping("/list")
    @HystrixCommand(fallbackMethod = "hystrixGetList")
    @Cacheable(cacheNames = "workProve", unless = "#result.getData() == null")
    //key:缓存数据时使用的 key，可以用它来指定。默认是使用方法参数的值；cacheNames/value：二者选其一即可，指定缓存组件的名字
    public Result queryById(@RequestParam(value = "projectId", required = false) Long projectId, @RequestParam(value = "workId", required = false) Long workId, @RequestParam(value = "userId", required = false) Long userId, @RequestParam(value = "startTime", required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") Date startTime, @RequestParam(value = "endTime", required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") Date endTime, @RequestParam(value = "createTime", required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") Date createTime) {
        QueryWrapper query = new QueryWrapper();
        if (projectId != null) {
            query.eq("project_id", projectId);
        }
        if (workId != null) {
            query.eq("work_id", workId);
        }
        if (userId != null) {
            query.eq("user_id", userId);
        }
        if (startTime != null && endTime != null && createTime != null) {
            return Result.fail("startTime，endTime，createTime不能同时有值，会矛盾");
        }
        if ((startTime != null && endTime == null) || (startTime == null && endTime != null)) {
            return Result.fail("startTime，endTime应该同时为空或同时不为空");
        }
        if (startTime == null && endTime == null && createTime != null) {
            query.eq("create_time", createTime);
        }
        if (startTime != null && endTime != null && createTime == null) {
            query.ge("create_time", startTime);
            query.le("create_time", endTime);
        }
        List<WorkProve> list = workProveService.list(query);
        if (list == null) {
            throw new RuntimeException("数据库没有该教师的workprove数据，或者信息无法找到");
        }
        return Result.succ(list);
    }

    public Result hystrixGetList(Long projectId, Long workId, Long userId, Date startTime, Date endTime, Date createTime) {
        return Result.fail("没有得到对应的workprove信息，或者刷新试试");
    }


    /*@PostMapping("/save")
    @Transactional
    //@RequestParam和@RequestPart的区别是：@RequestParam适用于name-valueString类型的请求域，@RequestPart适用于复杂的请求域（像JSON，XML）
    public Result save(OssDto ossDto) {
        if (ossDto.getProjectId() == null || ossDto.getProjectId().equals(""))
            return Result.fail("projectId不能为空，保存失败");
        if (ossDto.getWorkId() == null || ossDto.getWorkId().equals(""))
            return Result.fail("workId不能为空，保存失败");
        if (ossDto.getUserId() == null || ossDto.getUserId().equals(""))
            return Result.fail("userId不能为空，保存失败");

        String url = "";
        MultipartFile[] file = ossDto.getFile();
        WorkProve[] workProve = new WorkProve[file.length];
        for (int i = 0; i < file.length; i++) {
            workProve[i].setProjectId(ossDto.getProjectId());
            workProve[i].setWorkId(ossDto.getWorkId());
            workProve[i].setUserId(ossDto.getUserId());
        }
        for (int i = 0; i < file.length; i++) {
            url = ossService.uploadFileAvatar(file[i]);
            workProve[i].setFilePath(url);
            workProve[i].setCreateTime(DateUtil.date());
            workProveService.save(workProve[i]);
        }

        redisUtil.flushByX("workProve");
        return Result.succ(workProve);
    }*/
    @PostMapping("/save")
    @Transactional
    public Result save(@RequestParam(value = "projectId", required = false) Long projectId, @RequestParam(value = "workId", required = false) Long workId, @RequestParam(value = "userId", required = false) Long userId, HttpServletRequest request, HttpServletResponse response) throws Exception {
        System.out.println("//获取文件并保存==================");
        //将当前上下文初始化给  CommonsMutipartResolver （多部分解析器）
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
                request.getSession().getServletContext());
        List<WorkProve> list = new ArrayList<>();
        // 判断是否是多数据段提交格式
        if (multipartResolver.isMultipart(request)) {
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;

            System.out.println("以下获取上传的文件==");
            Iterator<String> iter = multiRequest.getFileNames();
            //进入到这。iter中的已经全部是文件类型了
            Integer fileCount = 0;
            while (iter.hasNext()) {
                String next = iter.next();
                Part part = multiRequest.getPart(next);
                String name = part.getName();
                System.out.println(name);
                //TODO
                MultipartFile file = multiRequest.getFile(next);
                System.out.println(file);
                if (file == null) {
                    System.out.println("没有文件");
                    break;
                } else {
                    WorkProve workProve = new WorkProve();
                    workProve.setWorkId(workId);
                    workProve.setProjectId(projectId);
                    workProve.setUserId(userId);
                    workProve.setCreateTime(DateUtil.date());
                    workProve.setFilePath(ossService.uploadFileAvatar(file).get());
                    boolean flag = workProveService.save(workProve);
                    if (flag) {
                        list.add(workProve);
                    }
                    fileCount++;
                }
            }
            System.out.println("本次提交文件类型的个数==" + fileCount);
        }
        return Result.succ(list);
    }

    @PostMapping("/delete")
    @Transactional
    public Result delete(@RequestParam Long id) {
        List<WorkRegister> workRegisters = workRegisterService.list();
        for (WorkRegister w : workRegisters) {
            String t = "";
            String[] st = w.getWorkProveId().split(",");
            for (int i = 0; i < st.length; i++) {
                if (Long.valueOf(st[i]) != id) {
                    if (t.equals("")) {
                        t += st[i];
                    } else {
                        t += "," + st[i];
                    }
                }
            }
            w.setWorkProveId(t);
            workRegisterService.updateById(w);
        }
        redisUtil.flushByX("workRegister");
        boolean flag = workProveService.removeById(id);
        if (flag) {
            redisUtil.flushByX("workProve");
            return Result.succ("删除成功");
        }
        return Result.fail("删除失败");
    }

    @PostMapping("/update")
    @Transactional
    public Result update(@RequestBody WorkProve workProve) {
        if (workProve.getProjectId() == null || workProve.getProjectId().equals(""))
            return Result.fail("projectId不能为空，更新失败");
        if (workProve.getWorkId() == null || workProve.getWorkId().equals(""))
            return Result.fail("workId不能为空，更新失败");
        if (workProve.getUserId() == null || workProve.getUserId().equals(""))
            return Result.fail("userId不能为空，更新失败");
        workProve.setCreateTime(DateUtil.date());
        boolean flag = workProveService.updateById(workProve);
        if (flag) {
            redisUtil.flushByX("workProve");
            return Result.succ(workProve);
        }
        return Result.fail("修改失败");
    }
}
